package templates

import (
	"embed"
	"html/template"
	"strings"

	"gitee.com/liumou_site/logger"
)

//go:embed index.html process-monitor.html
var templateFS embed.FS

// HtmlData 模板数据结构
type HtmlData struct {
	Hostname      string
	InterfaceName string
	Ipv4          string
	Version       string
	AppName       string
	Runtime       string
}

// RenderHtml 渲染HTML模板
type RenderHtml struct {
	indexTmpl        *template.Template
	processMonitorTmpl *template.Template
}

// NewRenderer 创建新的HTML渲染器
func NewRenderer() *RenderHtml {
	indexTmpl, err := template.ParseFS(templateFS, "index.html")
	if err != nil {
		logger.Error("Error parsing index template:", err)
		indexTmpl = template.Must(template.New("error").Parse(`<!DOCTYPE html><html><body><h1>主页模板加载错误</h1></body></html>`))
	}

	processMonitorTmpl, err := template.ParseFS(templateFS, "process-monitor.html")
	if err != nil {
		logger.Error("Error parsing process-monitor template:", err)
		processMonitorTmpl = template.Must(template.New("error").Parse(`<!DOCTYPE html><html><body><h1>进程监控模板加载错误</h1></body></html>`))
	}

	return &RenderHtml{
		indexTmpl:        indexTmpl,
		processMonitorTmpl: processMonitorTmpl,
	}
}

// GetHtmlText 生成主页HTML文本
func (r *RenderHtml) GetHtmlText(data HtmlData) string {
	var result strings.Builder
	if err := r.indexTmpl.Execute(&result, data); err != nil {
		logger.Error("Error executing index template:", err)
		return "<html><body>主页模板渲染错误</body></html>"
	}
	return result.String()
}

// GetProcessHtmlText 生成进程监控HTML文本
func (r *RenderHtml) GetProcessHtmlText(data HtmlData) string {
	var result strings.Builder
	if err := r.processMonitorTmpl.Execute(&result, data); err != nil {
		logger.Error("Error executing process-monitor template:", err)
		return "<html><body>进程监控模板渲染错误</body></html>"
	}
	return result.String()
}